﻿using System.Text;

namespace Code2Table.Core;

public static class MarkdownExporter
{
    /// <summary>
    /// 导出 Markdown 表格（仅四列：名称、类型、说明、必填，且可选择性输出）
    /// </summary>
    /// <param name="props">属性列表</param>
    /// <param name="useMySqlTypes">是否使用 MySQL 类型映射</param>
    /// <param name="columns">要输出的列，例如 ["名称", "类型", "说明", "必填"]，默认四列全输出</param>
    public static string ToMarkdown(List<PropertyInfoModel> props, bool useMySqlTypes = false,
        List<string>? columns = null)
    {
        if (props == null || props.Count == 0)
            return "_没有检测到任何属性_";

        // 默认输出全部四列
        columns ??= new List<string> { "名称", "类型", "说明", "必填" };

        // 确保只包含允许的四列
        var validColumns = new List<string> { "名称", "类型", "说明", "必填" };
        columns = columns.FindAll(c => validColumns.Contains(c));

        var sb = new StringBuilder();

        // 表头
        sb.Append("| ");
        sb.Append(string.Join(" | ", columns));
        sb.AppendLine(" |");

        // 分隔线
        sb.Append("| ");
        sb.Append(string.Join(" | ", columns.ConvertAll(_ => "------")));
        sb.AppendLine(" |");

        // 内容行
        foreach (var p in props)
        {
            var row = new List<string>();

            foreach (var col in columns)
            {
                row.Add(col switch
                {
                    "名称" => p.Name,
                    "类型" => GetDisplayType(p, useMySqlTypes),
                    "说明" => GetDescription(p),
                    "必填" => p.IsRequired ? "✅" : "",
                    _ => ""
                });
            }

            sb.Append("| ");
            sb.Append(string.Join(" | ", row));
            sb.AppendLine(" |");
        }

        return sb.ToString();
    }

    private static string GetDisplayType(PropertyInfoModel p, bool useMySqlTypes)
    {
        var type = useMySqlTypes ? TypeMapper.MapToMySql(p.Type) : p.Type;
        if (!string.IsNullOrEmpty(p.ColumnType))
            type = p.ColumnType; // 优先 Column(TypeName)
        return type;
    }

    private static string GetDescription(PropertyInfoModel p)
    {
        var desc = p.Description ?? "";
        if (p.MaxLength.HasValue && !desc.Contains("最大长度"))
            desc += (desc.Length > 0 ? "；" : "") + $"最大长度: {p.MaxLength}";
        if (!string.IsNullOrEmpty(p.Range))
            desc += (desc.Length > 0 ? "；" : "") + $"范围: {p.Range}";
        return desc;
    }
}